package il.ac.braude.sona.control;

import il.ac.braude.sona.database.User;
import il.ac.braude.sona.ocsf.Mssg;
import il.ac.braude.sona.ocsf.P;
import il.ac.braude.sona.ocsf.client.Client;
import il.ac.braude.sona.ocsf.client.ServerResponseListener;
import il.ac.braude.sona.ocsf.server.DatabaseController;
import il.ac.braude.sona.strings.Resources;
import il.ac.braude.sona.ui.forms.FormFrame;
import il.ac.braude.sona.ui.forms.FormListener;
import il.ac.braude.sona.ui.forms.myforms.LoginForm;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.JOptionPane;

public class LoginController implements FormListener {
	private User user;
	private LoginForm login;
	public User login() {
		login = new LoginForm();
		login.addFormListener(this);
		login.showFrame();
		synchronized(login) {
			try {
				login.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return user;
	}
	@Override
	public void onFormSubmited(final FormFrame formFrame, ArrayList<String> values) {
		try {
			Client c = Client.getInstance();
			login.showMessege(Resources.Strings.Connecting);
			Mssg mssg = new Mssg(P.login,values);
			c.sendToServer(new ServerResponseListener() {
				@SuppressWarnings("unchecked")
				@Override
				public void onServerResponse(Mssg mssg) {
					if (mssg.equals(P.error)) {
						login.showMessege((String) mssg.getMessege());
						return;
					}
					user = (User)mssg.getMessege();
					synchronized(login) {
						login.notify();
					}
					formFrame.dispose();
				}
			},mssg);
			 
		} catch (Exception e) {
			login.showMessege(Resources.Strings.ConnectFailed);
		}

	}
	@Override
	public void onFormCanceled(FormFrame formFrame) {
		System.exit(0);
	}

}
